<template>
  <div class="container" ref="container">
    <!-- 轮播图 -->
    <div class="SwiperBox" v-if="swiperData.length">
      <div class="swiperMain">
        <div style="margin: 0 auto; width: 1200px; position: relative">
          <div class="maskBox">
            <p
              class="banner-click-add"
              v-for="(item, index) in swiperData"
              :key="item.id"
            >
              <i
                :class="index == activeIndex ? 'banner-click-add_icon' : ''"
              ></i>
              <a
                @mouseenter="mouseenter(index)"
                @click="detail(item, index)"
                class="banner-click-add_txt"
                :title="item.name"
                :class="index == activeIndex ? 'colorBg' : ''"
                >{{ item.name }}</a
              >
            </p>
          </div>
        </div>

        <el-carousel
          direction="vertical"
          :autoplay="false"
          ref="carousel"
          indicator-position="none"
          @change="handleChange"
          v-model:active-index="activeIndex"
        >
          <el-carousel-item
            v-for="(item, index) in swiperData"
            :key="item.id"
            @click="detail(item, index)"
          >
            <!-- <ProcessedImage
              style="width: 100%"
              class="grid_img"
              :src="item.cover"
              :title="item.name"
              params="imageView2/2/h/280"
              :style="{
                backgroundSize: 'contain',
              }"
            /> -->
            <img
              style="width: 100%; height: 100%; object-fit: fill"
              :src="item.banner_img"
              :title="item.name"
              class="grid_img"
            />
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>

    <div class="Category_box">
      <div class="Category">
        <div class="Category_title">全部课程</div>
        <div class="fitterWrapper">
          <Category
            ref="category"
            :filterOptions="filterOptions"
            :selectedId="selectedId"
            :defaultSelected="[0, 0]"
            @updateSelected="updateSelected"
          ></Category>
        </div>
      </div>
    </div>

    <!-- <div class="bannerLogo" @click="zyPayClass">
      <img
        src="https://mcdn.chatgk.com/static/store/e43921190f65d6da8f7116756e17ee641/1726728785_jpg.jpg"
      />
    </div> -->

    <div class="search-wrapper" style="display: flex; align-items: center">
      <div style="margin-right: 10px">
        共 <span style="color: red">{{ total }}</span> 个课程
      </div>
      <div>
        <el-input
          style="width: 700px; height: 40px"
          v-model="tableConfig.search"
          clearable
          placeholder="课程名称"
          @clear="search"
        />
        <el-button
          id="searchBtn"
          style="
            background-color: #409eff;
            height: 42px;
            color: #fff;
            margin-left: -2px;
          "
          @click="search"
          >搜索</el-button
        >
      </div>
    </div>

    <div class="packs-wrapper" v-loading="loading">
      <!-- <div class="packs-wrapper-top">共 {{ total }} 个课程</div> -->
      <div class="packsData" v-if="tableData.length">
        <div class="ziYuanBox">
          <div
            class="grid-container"
            v-infinite-scroll="nextPage"
            :infinite-scroll-delay="500"
            :infinite-scroll-immediate="false"
          >
            <div
              class="grid-item"
              v-for="item in tableData"
              :key="item.id"
              @click="detail(item)"
            >
              <div class="coverUrl">
                <ProcessedImage
                  class="grid_img"
                  :src="item.cover"
                  :title="item.name"
                  params="imageView2/2/w/216/h/144"
                  v-if="item.cover"
                />
                <div class="sectionCount">共 {{ strArr(item.videos) }} 讲</div>
              </div>

              <div style="padding: 10px">
                <p class="grid_txt">
                  <span v-if="item.sign">{{ SIGN_NAME[item.sign] + '-' }}</span>
                  <span>{{ item.name }}</span>
                </p>
                <div class="sign_box">
                  <p class="grid_txt" style="color: #999">
                    {{ item.videoNum ?? 0 }} 播放
                  </p>
                  <p class="grid_txt" style="color: #e84c34; font-size: 24px">
                    <i
                      v-if="item.viewing_permission == 1"
                      class="iconfont icon-mianfei-xianxing"
                    ></i>
                    <i
                      v-if="item.viewing_permission == 2"
                      class="iconfont icon-VIP"
                    ></i>
                    <i
                      v-if="item.viewing_permission == 3"
                      class="iconfont icon-menzhenshoufei"
                    ></i>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="warn-box" v-else>
        <img src="https://staticv2.youzy.cn/images/usercenter/nodata.png" />
        <div class="info"><p>筛选条件后，暂无相关内容~</p></div>
      </div>
      <div id="noMore" v-if="tableData.length">以上为全部内容</div>
    </div>
    <zyBottom></zyBottom>
    <!-- <div class="clearboth" ref="clearboth">
      <div class="packs-wrapper_tags">
        <span class="fitterLeft">当前选择:</span>
        <span class="gotoSearch" href="#searchWrapper" @click="gotoSearch">
          <Search
            style="
              width: 1em;
              height: 1.2em;
              line-height: 19px;
              margin-left: 20px;
            "
          />
          <a href="#searchWrapper" style="margin-left: 15px; margin-top: 2px"
            >搜索</a
          >
        </span>
      </div>
    </div> -->
    <!-- 判断是否会员 -->
    <isVipDialog ref="isVipDialogShow" />
    <!-- 支付弹框 -->
    <Dialog
      v-model="modelValue"
      width="840"
      @closePayDialog="closePayDialog"
      @openClick="openClick"
    >
      <template #content>
        <div class="padding">
          <pay
            ref="payRerf"
            :detailList="detailList"
            :codeUrl="code_url"
            :formattedTime="formattedTime"
            :imgLoading="imgLoading"
            :resultPrice="resultPrice"
            :bannerInfoList="bannerInfoList"
            @payAll="payAll"
            @changePay="changePay"
          ></pay>
        </div>
        <!-- <div class="qrcode" v-loading="imgLoading" width="600">
          <img :src="code_url" alt="" class="qrImage" />
          <p>{{ goodsName }}</p>
          <p>{{ formattedTime }}</p>
        </div> -->
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import pay from '@/components/ziYuanLectureHall/components/payment_tab/index.vue';
import isVipDialog from '@/components/Dialog/isVipDialog';
import Dialog from '@/components/Dialog/payDialog.vue';
import QRCode from 'qrcode';
import {
  getvideoListApi,
  classTypeListApi,
  singleCoursePayApi,
  verifyApi,
  bannerInfoyApi,
  AlipayToolApi,
} from '@/api/zy/index';
import Category from '@/components/Category';
import zyBottom from '@/components/ziYuanLectureHall/components/index.vue';
import { ref, onMounted, onUnmounted, watchEffect, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
import { useNavigation } from '@/hooks/useNavigation';
const { goTo } = useNavigation();
// import { get } from 'lodash';
const category = ref('');
const container = ref(null);
const isVipDialogShow = ref(null);
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const modelValue = ref(false);

const activeIndex = ref(0);
const tableData = ref([]);
const swiperData = ref([]);
// const isFixed = ref(false); // 是否固定
const total = ref(0);
// const clearboth = ref(null);
const isLastPage = ref(false);
const timeRemaining = ref(300); // 倒计时时间，单位：秒（5 分钟）
const imgLoading = ref(false);
const code_url = ref('');
const out_trade_no = ref('');
const goodsName = ref('');
const paymentStatus = ref(''); // 支付状态：空、success、failed
const carousel = ref(null);
const selectedId = ref([]);
const statusPay = ref(true);
const bannerInfoList = ref([]);
const resultPrice = ref([]);
const detailList = ref([]);
const tableConfig = ref({
  search: '',
  page: 1,
  pageSize: 20,
  viewing_permission: '',
  type: '',
  status: '',
});
const SIGN_NAME = {
  1: '选修',
  2: '必修',
};
const classParams = ref({
  page: 1,
  pageSize: 100,
});
const swiperParams = ref({
  page: 1,
  pageSize: 5,
  recommend: 1,
});
const filterOptions = ref([
  {
    id: 38,
    pid: 0,
    name: '课程主题',
    type: 3,
    childs: [],
  },
  {
    id: 41,
    pid: 0,
    name: '课程价格',
    type: 2,
    childs: [
      { id: 1, name: '免费' },
      { id: 2, name: 'vip' },
      { id: 3, name: '收费' },
    ],
  },
]);
// const permission = ref({
//   1: '免费',
//   2: 'vip',
//   3: '收费',
// });
// const zyPayClass = () => {
//   router.push({ path: '/zYshopDet' });
// };
const payRerf = ref(null);
const closePayDialog = () => {
  payRerf.value.toggleText('false');
  payRerf.value.switchPayment('true');
  stopPolling();
};
const openClick = () => {
  payRerf.value.checkOverflow();
};

const updateSelected = (val, type) => {
  if (type) {
    tableData.value = [];
    tableConfig.value.page = 1;
    tableConfig.value.type = val[0] == 0 ? '' : val[0];
    tableConfig.value.viewing_permission = '';
    tableDataList();
    return;
  }
  tableData.value = [];
  tableConfig.value.page = 1;
  tableConfig.value.type = val.selectedIds[0] == 0 ? '' : val.selectedIds[0];
  tableConfig.value.viewing_permission =
    val.selectedIds[1] == 0 ? (val.selectedIds[1] = '') : val.selectedIds[1];
  tableDataList();
};
// 处理数据
const strArr = (item) => {
  return item ? item.split(',').length : 0;
};
const mouseenter = (index) => {
  activeIndex.value = index;
  carousel.value.setActiveItem(index);
};
const handleChange = (e) => {
  activeIndex.value = e;
};
// 搜索
const search = () => {
  tableData.value = [];
  tableConfig.value.page = 1;
  tableDataList();
};
// // 倒计时格式化为分钟和秒
const formattedTime = computed(() => {
  const minutes = Math.floor(timeRemaining.value / 60);
  const seconds = timeRemaining.value % 60;
  return (
    '请在' +
    `${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}` +
    '秒内完成支付'
  );
});

// 详情页面
const detail = async (item, index) => {
  // 轮播第一张跳转
  if (index == 0) {
    router.push({ path: '/zYshopDet' });
    return;
  }
  //  判断收费是否有试看
  const data = JSON.parse(item.videoSort);
  const isLook = data.some((item) => item.tryLook == true);
  goodsName.value = item.name;
  const isVIP = store.getters.user.userInfo.isVIP;
  const { viewing_permission } = item;
  if ((isVIP && viewing_permission == 2) || viewing_permission == 1) {
    goTo('/ziYclassroomsDetail', {
      query: {
        id: item.id,
        viewing_permission: item.viewing_permission,
        type: tableConfig.value.type,
      },
    });
  } else if (item.viewing_permission == 3) {
    if (item.is_verify) {
      goTo('/ziYclassroomsDetail', {
        query: {
          id: item.id,
          viewing_permission: item.viewing_permission,
          type: tableConfig.value.type,
        },
      });
      return;
    } else if (isLook) {
      goTo('/ziYclassroomsDetail', {
        query: {
          id: item.id,
          viewing_permission: item.viewing_permission,
          type: tableConfig.value.type,
        },
      });
      return;
    } else {
      detailList.value = item;
      modelValue.value = true;
      imgLoading.value = true;
      code({ id: item.id, type: 1 });
    }
  } else if ((isVIP == 1 || isVIP == 2) && item.viewing_permission == 2) {
    goTo('/ziYclassroomsDetail', {
      query: {
        id: item.id,
        viewing_permission: item.viewing_permission,
        type: tableConfig.value.type,
      },
    });
    return;
  } else if (isVIP == 3 && item.viewing_permission == 2) {
    isVipDialogShow.value.openDialog();
  } else {
    isVipDialogShow.value.openDialog();
  }
};
const code = async (params) => {
  const data = statusPay.value
    ? await singleCoursePayApi(params)
    : await AlipayToolApi(params);
  if (data.data.code == 20000) {
    out_trade_no.value = data.data.data.out_trade_no;
    QRCode.toDataURL(data.data.data.code_url)
      .then((url) => {
        code_url.value = url;
        timeRemaining.value = 300; // 重置倒计时
        startCountdown(); // 开始倒计时
        startPolling(); // 开始轮询
        imgLoading.value = false;
      })
      .catch((error) => {
        console.error('二维码生成失败:', error);
      });
  }
};
const payAll = (val) => {
  // 购买全部课程
  code(val);
};
// 切换支付
const changePay = ({ params, index }) => {
  statusPay.value = !statusPay.value;
  index == 0 ? code({ id: detailList.value.id, type: 1 }) : code(params);
};
// 倒计时逻辑
let countdownInterval;
const startCountdown = () => {
  clearInterval(countdownInterval); // 清除之前的倒计时
  countdownInterval = setInterval(() => {
    if (timeRemaining.value > 0) {
      timeRemaining.value -= 1;
    } else {
      clearInterval(countdownInterval); // 倒计时结束时停止计时
      stopPolling(); // 停止轮询
    }
  }, 1000);
};

// 轮询支付状态逻辑
let pollingInterval;
const startPolling = () => {
  clearInterval(pollingInterval); // 清除之前的轮询
  pollingInterval = setInterval(async () => {
    try {
      const response = await verifyApi({ out_trade_no: out_trade_no.value }); // 模拟后端请求
      if (response.data.msg === '购买成功') {
        tableData.value = [];
        paymentStatus.value = '购买成功';
        clearInterval(pollingInterval); // 停止轮询
        clearInterval(countdownInterval); // 停止倒计时
        tableDataList();
        modelValue.value = false;
      }
    } catch (error) {
      console.error('轮询支付状态失败:', error);
    }
  }, 5000); // 每 5 秒轮询一次
};

// 停止轮询
const stopPolling = () => {
  clearInterval(pollingInterval);
};
const nextPage = () => {
  if (isLastPage.value) return;
  tableConfig.value.page += 1;
  tableDataList();
};

// 课程类别
const classTypeList = async () => {
  const { data } = await classTypeListApi(classParams.value);
  resultPrice.value = data.data;
  filterOptions.value[0].childs = data.data.data;
  filterOptions.value[0].childs.unshift({ id: 0, name: '不限' });
};
// 视频列表
const tableDataList = async () => {
  loading.value = true;
  try {
    const { data } = await getvideoListApi(tableConfig.value);
    isLastPage.value = tableConfig.value.page == data.data.last_page;
    tableData.value = [...tableData.value, ...data.data.data];
    tableData.value = tableData.value.filter((item) => item.status == 1);
    total.value = data.data.total;
    loading.value = false;
  } catch (err) {
    console.log(err);
  }
};
// const handleScroll = () => {
//   const scrollTop = Math.floor(
//     window.pageYOffset ||
//       document.documentElement.scrollTop ||
//       document.body.scrollTop,
//   );
//   if (scrollTop > 280) {
//     isFixed.value = true;
//     clearboth.value.style.position = 'fixed';
//     clearboth.value.style.display = 'block';
//   } else {
//     clearboth.value.style.position = 'none';
//     clearboth.value.style.display = 'none';
//   }
// };
// const gotoSearch = () => {
//   window.scrollTo({
//     top: 260, // 滚动到距离顶部 300 像素的位置
//     behavior: 'smooth',
//   });
// };
// 轮播图
const swiperList = async () => {
  try {
    const { data } = await getvideoListApi(swiperParams.value);
    swiperData.value = [...swiperData.value, ...data.data.data];
  } catch (err) {
    console.log(err);
  }
};
// 第一个轮播跳转
const bannerInfo = async () => {
  const data = await bannerInfoyApi();
  bannerInfoList.value = data.data.data;
  if (bannerInfoList.value.off == 2) {
    swiperList();
  }

  if (bannerInfoList.value.off != 2) {
    swiperData.value.unshift({
      banner_img: bannerInfoList.value.banner,
      name: bannerInfoList.value.title,
      infoBanner: bannerInfoList.value.infoBanner,
    });
    if (swiperData.value.length) {
      swiperList();
    }
  }
};
onMounted(() => {
  // window.addEventListener('scroll', handleScroll);
  classTypeList();
  bannerInfo();
  if (route.query.id) {
    selectedId.value[0] = route.query.id ? Number(route.query.id) : '';

    tableConfig.value.type = route.query.id == 0 ? '' : route.query.id;
  }
  tableDataList();
});

watchEffect(() => {
  // 回显选中的id
  if (route.query.type) {
    selectedId.value[0] = route.query.type;
    selectedId.value[1] = 0;
  }
});
watch(
  () => route.query.id, // 监听目标
  (newValue) => {
    selectedId.value[0] = newValue ? Number(newValue) : newValue;
    selectedId.value[1] = 0;
    updateSelected(selectedId.value, 'type');
  },
);
onUnmounted(() => {
  // window.removeEventListener('scroll', handleScroll);
});
// 提供方法给后代组件
</script>
<style lang="scss" scoped src="./index.scss"></style>
